package entity

import (
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"nspel/nspel"
	"strconv"
)

type Tag struct {
	StudentId int64 `orm:"pk;column(student_id)"`
	LabelId   int64 `orm:"column(label_id)"`
}

func init() {
	orm.RegisterModel(new(Tag))
}

func (t *Tag) TableName() string {
	return "tag"
}

func (t *Tag) SelectAllByStudentId(studentId int64) (tags []Tag, err error) {
	key := "tag"
	hashKey := "studentId[" + strconv.FormatInt(studentId, 10) + "]"
	err = nspel.RedisHgetJson(key, hashKey, &tags)
	if err == nil {
		return
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	_, err = nspel.GetOrmEngine().QueryTable(t.TableName()).Filter("student_id", studentId).All(&tags)
	if err != nil || len(tags) == 0 {
		return
	}
	nspel.RedisHsetJson(key, hashKey, tags)
	return
}

func (t *Tag) DeleteByStudentIdLabelId(studentId int64, labelId int64) (err error) {
	t.StudentId = studentId
	t.LabelId = labelId
	_, err = nspel.GetOrmEngine().Delete(t, "student_id", "label_id")
	return err
}

func (t *Tag) SelectAllByStudentIdLabelId(studentId int64, labelId int64) (err error) {
	key := "tag"
	hashKey := "studentId[" + strconv.FormatInt(studentId, 10) + "].labelId[" + strconv.FormatInt(labelId, 10) + "]"
	err = nspel.RedisHgetJson(key, hashKey, t)
	if err == nil {
		return
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	t.StudentId = studentId
	t.LabelId = labelId
	err = nspel.GetOrmEngine().Read(t, "student_id", "label_id")
	if err != nil {
		return
	}
	nspel.RedisHsetJson(key, hashKey, t)
	return
}

func (t *Tag) Insert() (err error) {
	_, err = nspel.GetOrmEngine().Insert(t)
	return
}
